package com.razorthink.shell.commands.essential;

import java.io.IOException;
import java.sql.SQLException;

import com.razorthink.shell.core.AbstractCommand;
import com.razorthink.shell.core.ShellIO;
import com.razorthink.shell.core.entities.User;
import com.razorthink.shell.utils.CommandLogger;
import com.razorthink.shell.utils.DerbyDB;

public class Login extends AbstractCommand {
	DerbyDB db;

	public Login(String baseCommand, int params) {
		super(baseCommand, params);
	}

	@Override
	public void execute() {
		String oldPrompt = super.getAppContext().getPrompt();
		if (oldPrompt.contains("@")) {
			CommandLogger
					.logInfo("Other user is already logged in. You have to logout to login as a different user.");
			return;
		}
		try {
			db = DerbyDB.getInstance();
		} catch (Exception e) {
			System.out.println("DB error: " + e.getMessage());
			CommandLogger.logError(e);
			return;
		}
		if (super.getCommandParser().getParamCount() > 0) {
			CommandLogger.logInfo("Login command cannot have param");
			return;
		}
		try {
			String userName = ShellIO.read("Username: ");
			String passWord = ShellIO.read("Password for '" + userName + "': ");
			// String passWord = ShellIO.maskedRead("Password for '" + userName
			// + "': ");
			try {
				User user = db.validateUser(userName, passWord);
				if (user == null)
					CommandLogger.logInfo("Invalid credentials.");
				else {
					super.getAppContext().setPrompt(
							user.getName() + "@"
									+ super.getAppContext().getPrompt());
					CommandLogger.logInfo("Logged In.");
					super.setEnvVar("loggedin", user);
					db.updateLogin(user.getName(), System.currentTimeMillis());
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public String getDescription() {
		return "login as a user";
	}

	@Override
	public String getUsage() {
		return "login";
	}

}
